﻿using MediatR;
using Warehouse.Domain;
using Warehouse.Domain.DTO;
using Warehouse.Infrstructre.Interface;
using Warehouse.Read.API.Applcation.Command.StorehouseCommand;
namespace Warehouse.Read.API.Applcation.CommandHandlers.StorehouseCommandhandlers
{
    public class SelectStorehouseCommanndHandlers:IRequestHandler<SelectStorehouseCommannd,PageDTO<StoreWareDTO>>
    {
        private readonly IStorehouseRepository _storehouse;
        private readonly IWarehouseRepository _warehouse;

        public SelectStorehouseCommanndHandlers(IStorehouseRepository _storehouse, IWarehouseRepository _warehouse)
        {
             this._storehouse = _storehouse;
             this._warehouse = _warehouse;
        }

        public async Task<PageDTO<StoreWareDTO>> Handle(SelectStorehouseCommannd request, CancellationToken cancellationToken)
        {


            var list = (from a in await _storehouse.GetAllAsyns()
                        join b in await _warehouse.GetAllAsyns() on a.WarehouseId equals b.WarehouseId
                        where a.IsDel == false && b.IsDel == false && a.office_id == request.Oid
                        select new StoreWareDTO
                        {

                            StorehouseCode = a.StorehouseCode,
                            StorehouseName = a.StorehouseName,
                            WarehouseName = b.WarehouseName,
                            WarehouseId = b.WarehouseId,
                            StorehouseId = a.StorehouseId,
                            StorehouseType = a.StorehouseType,
                            IsDisable = a.IsDisable,
                            IsDefaults = a.IsDefaults,
                            CreatTime = a.CreatTime,
                            Sremark = a.Sremark,
                        });
            if (!string.IsNullOrEmpty(request.StoreCode))
            {
                list = list.Where(x => x.StorehouseCode.Contains(request.StoreCode)).ToList();
            }
            if (!string.IsNullOrEmpty(request.StoreName))
            {
                list = list.Where(x => x.StorehouseName.Contains(request.StoreName)).ToList();
            }
            
            if (request.wid > 0)
            {
                list = list.Where(x => x.WarehouseId == request.wid).ToList();
            }
            //if (!string.IsNullOrEmpty(request.Oid))
            //{
            //    list = list.Where(x => x.office_id == request.Oid).ToList();
            //}
       
            PageDTO<StoreWareDTO> page = new PageDTO<StoreWareDTO>();

            page.Totalcount = list.Count();
            page.Pagecount = (int)Math.Ceiling(page.Totalcount * 1.0 / (int)request.PageSize);
            page.list = list.OrderByDescending(x => x.StorehouseId).Skip((request.pageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();

            return page; ;
        }
    }
}
